﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using PSE.Deployment.Engine.CustomExceptions;
using PSE.Deployment.Engine.Interfaces;
using PSE.Deployment.SetupBase.Configuration;
using PSE.Deployment.SetupBase.Parameter;

namespace PSE.Deployment.SetupBase.Steps
{
    public class InstallProcessManagerProduct : SetupStep<Configuration.Actions.InstallProcessManagerProduct>
    {
        public InstallProcessManagerProduct(IStepGroup parent, Group group, Configuration.Actions.InstallProcessManagerProduct action, Parameter.Enums.SetupMode setupMode)
            : base(parent, group, action, setupMode)
        {
            this.ResetProgress(1);
        }

        public override void Execute()
        {
            this.ResetProgress(1);

            if (this.SetupMode == Parameter.Enums.SetupMode.Install)
            {
                InstallProduct();
            }
            else if (this.SetupMode == Parameter.Enums.SetupMode.Uninstall)
            {
                UninstallProduct();
            }
        }

        public override void Undo()
        {
            if (this.SetupMode == Parameter.Enums.SetupMode.Install)
            {
                UninstallProduct();
            }
        }

        private void InstallProduct()
        {
            this.IncrementProgress(Action.ProductName);

            PSE.Deployment.Util.ProcessManager.GetInstance().AddProduct(Action.ProductName);
        }

        private void UninstallProduct()
        {
            this.DecrementProgress(Action.ProductName);

            try
            {
                PSE.Deployment.Util.ProcessManager.GetInstance().RemoveProduct(Action.ProductName);
            }
            catch (Exception ex)
            {
                SetupMainFactory.GetInstance().WriteStepLog(this, string.Format("Não foi possível desinstalar o produto {0}", Action.ProductName), ex);
            }
        }
    }
}
